<?php


namespace services\patient;

use common\components\Service;
use common\helpers\DateHelper;
use common\helpers\RedisHelper;
use common\models\patient\Patient;
use common\models\patient\PatientConsume;
use common\models\patient\PatientOrder;
use Yii;

class PatientConsumeService extends Service
{
    /**
     * 消费列表
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0): array
    {
        $query = PatientConsume::find()->alias('pc')
            ->select([
                'po.id order_id', 'po.order_time', 'po.shop_id', 'po.treatment_project_id',
                'p.id', 'p.name', 'p.type_id', 'p.created_at',
            ])
            ->innerJoin(Patient::tableName().' p', 'p.id = pc.patient_id')
            ->where([
                'p.user_id' => Yii::$app->user->identity->member_id,
                'p.status' => Patient::STATUS_ENABLE
            ]);
        if (isset($params['name']) && $params['name']) {
            $query->andWhere(['like', 'p.name', $params['name']]);
        }
        // 排序
        $order = [
            'po.order_time' => SORT_DESC,
            'po.id' => SORT_DESC,
        ];

        return $this->getListPageRes($query, $page, $pageSize, $order);
    }

    /**
     * 格式化列表
     * @param array $data
     * @return array
     */
    public function getListPageFormat(array $data = []): array
    {
        $list = [];
        foreach ($data as $row) {
            $list[] = [
                'id' => $row['id'],
                'order_id' => $row['order_id'],
                'shop_name' => RedisHelper::getShop($row['shop_id'])->name ?? '',
                'name' => $row['name'],
                'treatment_project' => RedisHelper::getTreatmentProject($row['treatment_project_id'])->name ?? '',
                'type_str' => RedisHelper::getPatientType($row['type_id'])->name ?? '',
                'created_at_str' => DateHelper::timestampToDate($row['created_at'], DateHelper::DATE_FORMAT_1),
                'order_time_str' => DateHelper::timestampToDate($row['order_time'], DateHelper::DATE_FORMAT_1),
            ];
        }
        return $list;
    }

    /**
     * 患者最近一次预约记录
     * @param int|array $ids
     * @return PatientOrder[]
     */
    public static function getPatientLastOrderMap($ids): array
    {
        return PatientOrder::find()
            ->where(['id' => $ids])
            ->indexBy('patient_id')
            ->all();
    }
}
